<template>
<div style="position: relative; display: flex; justify-content: center; align-items: center; width: 100%; height: 100vh;">
    <div ref="lottieContainer" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"></div>
    <div style="position: relative; z-index: 1; text-align: center; color: white;">
          <!--登录-->
          <el-card v-loading="loading" v-if="formtype==='登录'">
            <div style="display: flex; justify-content: center">
                <h2 style="font-family: Arial, sans-serif;font-size: 30px">{{ $t('登录系统') }}</h2>
            </div>
            <el-form :model="ruleForm" ref="ruleFormRef">
                <el-form-item prop="name">
                    <el-input :prefix-icon="Avatar" v-model="ruleForm.name" clearable style="width: 300px" />
                </el-form-item>
                <el-form-item prop="pass">
                    <el-input v-model="ruleForm.pass" show-password :prefix-icon="Lock" type="password" style="width: 300px" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="login(ruleFormRef)" style="width: 300px; font-size: 16px">{{ $t('登录') }}</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button color="#0089b5" @click="GoToResister" style="width: 300px; font-size: 16px">{{ $t('注册') }}</el-button>
                </el-form-item>
                <el-form-item>
                    <!-- <router-link to="/">{{ $t('忘记密码?') }}</router-link> -->
                    <el-button type="danger" >{{ $t('忘记密码?') }}</el-button>
                </el-form-item>

                <el-form-item>
                    <el-dropdown>
                        <span>
                            {{ $t('切换语言') }}
                            <el-icon><arrow-down /></el-icon>
                        </span>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item @click="switchLanguage('en')">en</el-dropdown-item>
                                <el-dropdown-item @click="switchLanguage('zh')">zh</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </el-form-item>
            </el-form>
        </el-card>
        <!--注册-->
        <el-card v-loading="loading" v-if="formtype==='注册'">
            <div style="display: flex; justify-content: center">
                <h2 style="font-size: 30px">{{ $t('注册账号') }}</h2>
            </div>
            <el-form :model="ruleForm" ref="ruleFormRef" label-width="80">
                <el-form-item :label="$t('姓名')" prop="name">
                    <el-input clearable v-model="ruleForm.name" :placeholder="$t('姓名')" />
                </el-form-item>
                <el-form-item :label="$t('电话')" prop="tel">
                    <el-input clearable v-model="ruleForm.tel" />
                </el-form-item>
                <el-form-item :label="$t('密码')" prop="pass">
                    <el-input show-password v-model="ruleForm.pass" type="password" autocomplete="off" />
                </el-form-item>
                <el-form-item :label="$t('确认密码')" prop="checkPass">
                    <el-input show-password v-model="ruleForm.checkPass" type="password" autocomplete="off" />
                </el-form-item>
                <el-form-item>
                    <div style="margin-right: 50px">
                        <el-button color="#d3d3d3" @click="resetForm(ruleFormRef)">{{ $t('重置') }}</el-button>
                        <el-button color="#1b62ab" @click="register(ruleFormRef)">{{ $t('注册') }}</el-button>
                    </div>
                </el-form-item>
                <el-form-item style="margin-right: 80px">
                    <!-- <router-link to="/login">{{ $t('已有账号?') }}</router-link> -->
                     <el-button type="success"  @click="GoToLogin" >{{ $t('已有账号?') }}</el-button>
                </el-form-item>
                <el-form-item style="margin-right: 80px">
                    <el-dropdown>
                        <span style="font-size: 16px">
                            {{ $t('切换语言') }}
                            <el-icon><arrow-down /></el-icon>
                        </span>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item @click="switchLanguage('en')">en</el-dropdown-item>
                                <el-dropdown-item @click="switchLanguage('zh')">zh</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</div>
</template>

<script lang="ts" setup>
import { getCurrentInstance, onMounted, reactive, ref, computed } from 'vue';
import type { FormInstance } from 'element-plus';
import { httpSend } from '../../utils/api';
import { useI18n } from 'vue-i18n';
import { Avatar, Lock } from '@element-plus/icons-vue';
// 引入 Pinia store
import { usetabsStore,useusrStore} from '@/store';
import { useRouter } from 'vue-router';
// 使用 vue-i18n 提供的 useI18n API
const { locale } = useI18n();
import { ElMessage } from 'element-plus'
import lottie from 'lottie-web';
import animationData from '@/assets/animate.json';
import { usegrantStore} from '@/store';

const grantStore = usegrantStore() as any;
const lottieContainer = ref(null);


const switchLanguage = (language) => {
    localStorage.setItem('locale', language);
    locale.value = language;
};
const userstore = useusrStore() as any;
const tabStore = usetabsStore() as any;
const router = useRouter();
const { t } = useI18n(); //多语言
const loading = ref(false); //加载状态
const ruleFormRef = ref<FormInstance>();
const { appContext } = getCurrentInstance(); //获取当前实例
const formtype=ref('登录');//判断操作类型
const ruleForm = reactive({
    name: '',
    tel: '',
    pass: '',
    checkPass: '',
}); //表单数据

// Created钩子
onMounted(() => {
    if (!!localStorage.getItem('loginout')) {
        userstore.logout();
        localStorage.removeItem('user');
        ElMessage({
            title: t('注意'),
            message: t('登录已过期,请先登录'),
            type: 'warning',
            border: true,
        });
        localStorage.removeItem('loginout');
    }
    lottie.loadAnimation({
    container: lottieContainer.value,
    renderer: 'svg',
    loop: true,
    autoplay: true,
    animationData: animationData, // 导入动画背景
  });
});

const GoToResister = () => {
    //router.push('/register');
    ruleForm.name='';
    ruleForm.tel='';
    ruleForm.pass='';
    ruleForm.checkPass='';
    formtype.value='注册';
};

const GoToLogin = () => {
    //router.push('/login');
    ruleForm.name='';
    ruleForm.tel='';
    ruleForm.pass='';
    ruleForm.checkPass='';
    formtype.value='登录';
};

const login = async (formEl: FormInstance | undefined) => {
    // 将函数声明为 async
    if (!formEl) {
        console.log('noform');
        return;
    }
    // validate 内部的回调不需改为 async
    formEl.validate(async (valid) => {
        if (valid) {
            const fd = new FormData();
            fd.append('name', ruleForm.name);
            fd.append('password', ruleForm.pass);
            loading.value = true;
            try {
                const res = await httpSend('login', fd);
                if (res.code === 1) {
                    userstore.setAtoken(res.token);
                    userstore.setuserid(res.data.id);
                    userstore.setusername(res.data.name);
                    userstore.setuserinfo(res.data);
                    tabStore.setnull();
                    router.push('/dashboard');
                    loadgrant();
                } else {
                    console.log('失败');
                }
            } catch (error) {
                console.error('请求失败', error);
            } finally {
                loading.value = false;
            }
        } else {
            console.log('error submit!');
        }
    });
};

//加载用户权限
const loadgrant = async () => {
    const res = await httpSend('loadgrant', {},false);
    if (res.data) {
        grantStore.setisadmin(res.isadmin);
        grantStore.setgrantlist(res.data);
    }
};

const register = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate(async (valid) => {
        if (valid) {
            try {
                loading.value = true;
                const fd = new FormData();
                fd.append('name', ruleForm.name);
                fd.append('tel', ruleForm.tel);
                fd.append('password', ruleForm.pass);
                fd.append('password_confirmation', ruleForm.checkPass);
                const res = await httpSend('register', fd);
                if (res.code === 1) {
                    //router.push('/login');
                    formtype.value='登录';
                } else {
                    console.log('失败');
                }
            } catch (error) {
                console.error('请求失败', error);
            } finally {
                loading.value = false;
            }
        } else {
            console.log('error submit!');
        }
    });
};
</script>

<style scoped>
.el-card {
    --el-card-border-color: var(--el-border-color-light);
    --el-card-border-radius: 4px;
    --el-card-padding: 20px;
    --el-card-bg-color: var(--el-fill-color-blank);
    background-color: var(--el-card-bg-color);
    border: 1px solid var(--el-card-border-color);
    border-radius: var(--el-card-border-radius);
    color: var(--el-text-color-primary);
    overflow: hidden;
    transition: var(--el-transition-duration);
    width: 400px;
    height: 500px;
    border-radius: 25px;
    background: rgba(255, 255, 255, 0.5);
}

:deep(.el-form-item__content) {
    align-items: center;
    display: flex;
    flex: 1;
    flex-wrap: wrap;
    font-size: var(--font-size);
    line-height: 32px;
    min-width: 0;
    position: relative;
    justify-content: center;
}
</style>
